package com.seednia.module.util.template.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seednia.foundation.framework.service.AbstractService;
import com.seednia.module.util.template.service.ITemplate;
import com.seednia.module.util.template.service.ITemplateFactory;
import com.seednia.module.util.template.service.ITemplateService;

/**
 * Template provider service
 * 
 * @author Young Suk Ahn
 *
 */
public class TemplateDefaultService extends AbstractService implements ITemplateService {

	private Map<String, ITemplate> templateMap = new HashMap<String, ITemplate >();
	
	private Set<ITemplateFactory> templateFactories = null;
	
	private static final Log logger = LogFactory.getLog(TemplateDefaultService.class);
	
	@Override
	public void initialize() {
		this.templateFactories = new HashSet<ITemplateFactory>();
		// load templates
		Properties props = new Properties();
		//props.setProperty(ITemplateFactory.TEMPLATE_LOADER_PATH, "/resource");
		props.put(ITemplateFactory.TEMPLATE_LOADER_CLASSPATH, getClass());
		
		
		ITemplateFactory fmtf = new FreeMarkerTemplateFactory();
		try {
			fmtf.initialize(props);
			templateFactories.add(fmtf);
		} catch (IOException e) {
			logger.error("Exception while initializing Template Factory", e);
			e.printStackTrace();
		}
	}

	@Override
	public ITemplate getTemplate(String name) {
		ITemplate retval = null;
		if (templateMap.containsKey(name)) {
			retval = templateMap.get(name);
		} else {
			for (ITemplateFactory tplFactory: templateFactories) {
				try {
					retval = tplFactory.getTemplate(name);
					if (retval != null ) {
						templateMap.put(name, retval);
						break;
					}
				} catch (IOException e) {
					//e.printStackTrace();// ignore, just try the next factory;
				}
			}
			if (retval == null)
				throw new IllegalArgumentException("Template ["+name+"] not found");
		}
		return retval;
	}

}
